#include "mainwindow.h"
#include <QMouseEvent>
#include <QPainter>
#include <QPixmap>
#include <QDebug>
#include "main.h"
#include <QFile>

MainWindow::MainWindow(QWidget *parent)
    : QWidget(parent)
{
    this->setMouseTracking(true);
    dialog     = new YouWin();
    ChessBoard = new QPixmap(":img/ChessBoard.jpg");
    BlackChess = new QPixmap(":img/BlackChess.jpg");
    WhiteChess = new QPixmap(":img/WhiteChess.jpg");
    socket     = new QTcpSocket();
    server     = new QTcpServer();
    this->setFixedSize(ChessBoard->width(),ChessBoard->height());
    this->setWindowTitle("五子棋单机版");
    cols        = 15;
    rows        = 15;
    width_block = 48;
    width_line  = 2;
    Chess= (int**)malloc(rows*sizeof(int*));
    for(int i=0;i<rows;i++)
    {
        Chess[i] = (int*)malloc(cols*sizeof(int));
        for(int j=0;j<cols;j++)
        {
            Chess[i][j] = 0;
        }
    }
    connect(dialog->btn,&QPushButton::clicked,this,[=](){this->close();dialog->close();});
    connect(this,&MainWindow::win,this,[=](){dialog->show();});
    QFile* file = new QFile("E:\\Qt\\Gobang\\info.txt");
    if(!file->open(QIODevice::ReadOnly))
    {
        qDebug()<<"资源文件打不开！";
        return;
    }
    QByteArray content=file->readAll();
    QString IP = getIP(content);
    char* ID   = getID(content);
    file->close();
    if(strcmp(ID,"Client")==0)
    {
        youAreReady = 0; // 白子后手
        socket->connectToHost(QHostAddress(IP),8888);
        connect(socket,&QTcpSocket::connected,this,
                [=]()
        {
            connect(socket,&QTcpSocket::readyRead,this,
                    [=]()
            {
                QByteArray arr=socket->readAll(); // arr[0]是对手棋所在行数，arr[1]是对手棋所在列数
                char* res = arr.data();
                int i,j;
                if(res[0]>='0'&&res[0]<='9')
                    i = res[0]-'0';
                else
                    i = res[0]-'a'+10;
                if(res[1]>='0'&&res[1]<='9')
                    j = res[1]-'0';
                else
                    j = res[1]-'a'+10;
                Chess[i][j] = -1;
                this->update();
            });
        });
    }
    if(strcmp(ID,"Server")==0)
    {
        connect(server,&QTcpServer::newConnection,this,
                [=]()
        {
            youAreReady = 1; // 黑子先手
        });
        connect(socket,&QTcpSocket::readyRead,this,
                [=]()
        {
            QByteArray arr=socket->readAll(); // arr[0]是对手棋所在行数，arr[1]是对手棋所在列数
            char* res = arr.data();
            int i,j;
            if(res[0]=='x'&&res[0]=='x')
            {
                //你输了
                return;
            }
            if(res[0]>='0'&&res[0]<='9')
                i = res[0]-'0';
            else
                i = res[0]-'a'+10;
            if(res[1]>='0'&&res[1]<='9')
                j = res[1]-'0';
            else
                j = res[1]-'a'+10;
            Chess[i][j] = 1;
            this->update();
        });
    }
    if(strcmp(ID,"WTF")==0)
    {
        qDebug()<<"WTF!!!";
    }
}
void MainWindow::paintEvent(QPaintEvent* e)
{
    Q_UNUSED(e);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.drawPixmap(0,0,ChessBoard->width(),ChessBoard->height(),*ChessBoard);
    for(int i=0;i<rows;i++)
    {
        for(int j=0;j<cols;j++)
        {
            if(Chess[i][j] == 1)
            {
                painter.drawPixmap(j*width_line+width_block/2+width_block*j,i*width_line+width_block/2+width_block*i,WhiteChess->width(),WhiteChess->height(),*WhiteChess);
            }
            if(Chess[i][j] == -1)
            {
                painter.drawPixmap(j*width_line+width_block/2+width_block*j,i*width_line+width_block/2+width_block*i,BlackChess->width(),BlackChess->height(),*BlackChess);
            }
        }
    }
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if(!youAreReady)
        return;
    if(Chess[event->y()/(width_block+width_line)][event->x()/(width_block+width_line)]==0)
    {
        if(x==-1 && y==-1)
        {
            Chess[event->y()/(width_block+width_line)][event->x()/(width_block+width_line)] = -1;
            x = event->y()/(width_block+width_line);
            y = event->x()/(width_block+width_line);
        }
        else
        {
            if(event->y()/(width_block+width_line)<rows && event->x()/(width_block+width_line)<cols)
            {
                Chess[x][y] = 0;
                Chess[event->y()/(width_block+width_line)][event->x()/(width_block+width_line)] = -1;
                x = event->y()/(width_block+width_line);
                y = event->x()/(width_block+width_line);
            }
        }
    }
    update();
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if(!youAreReady)
        return;
    if(event->button() == Qt::LeftButton)
    {
        int i = event->y()/(width_block+width_line);
        int j = event->x()/(width_block+width_line);
        x = -1;
        y = -1;
        if(Chess[i][j] == 0)
        {
            Chess[i][j] = -1;
        }
        char location[2] = {'\0','\0'};
        if(getSituation(i,j)==5)
        {
            location[0] = 'x';location[1] = 'x';
            QString str(location);
            socket->write(str.toUtf8().data());
            return;
        }
        if(i<10)
        {
            location[0] = i+'0';
        }
        else
        {
            location[0] = i+'a'-10;
        }
        if(j<10)
        {
            location[1] = j+'0';
        }
        else
        {
            location[1] = j+'a'-10;
        }
        QString str(location);
        socket->write(str.toUtf8().data());
    }
    update();
}
int MainWindow::getSituation(int x,int y)
{
    int num=0;
    int xtmp = x;
    int ytmp = y;
    while(xtmp < rows && Chess[xtmp][ytmp] == Chess[x][y]){num++;xtmp++;}
    xtmp = x-1;
    while(xtmp >= 0 && Chess[xtmp][ytmp] == Chess[x][y]){num++;xtmp--;}
    if(num >= 5)
        return 5;
    else
    {
        xtmp = x;ytmp = y;num = 0;
        while(ytmp < cols && Chess[xtmp][ytmp] == Chess[x][y]){num++;ytmp++;}
        ytmp = y-1;
        while(ytmp >= 0 && Chess[xtmp][ytmp] == Chess[x][y]){num++;ytmp--;}
        if(num >= 5)
            return 5;
        else
        {
            xtmp = x;ytmp = y;num = 0;
            while(ytmp < cols && xtmp < rows && Chess[xtmp][ytmp] == Chess[x][y]){num++;ytmp++;xtmp++;}
            xtmp = x-1;ytmp = y-1;
            while(ytmp >= 0 && xtmp >= 0 && Chess[xtmp][ytmp] == Chess[x][y]){num++;ytmp--;xtmp--;}
            if(num >= 5)
                return 5;
            else
            {
                xtmp = x;ytmp = y;num = 0;
                while(x >= 0 && y < cols && Chess[xtmp][ytmp] == Chess[x][y]){num++;ytmp++;xtmp--;}
                xtmp = x-1;ytmp = y-1;
                while(x < rows && y >= 0 && Chess[xtmp][ytmp] == Chess[x][y]){num++;ytmp--;xtmp++;}
                if(num >= 5)
                    return 5;
                else
                    return 0;
            }
        }
    }
}
MainWindow::~MainWindow()
{
}

